package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.security.MD5;
import com.xgkj.diyiketang.task.BangDingShouJiTask;
import com.xgkj.diyiketang.task.ForgetPswTask;
import com.xgkj.diyiketang.task.GetVerifyCodeTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.yizhibo.Preferences;

/**
 * Created by Administrater on 2015/12/10.
 */
public class BangDingPhoneActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "ForgetPswActivity";
    private static final int PHONE_LENGTH = 11;
    private static final String PHONE_REGEX = "1[34578]\\d{9}";
    private static final int CODE_LENGTH = 6;
    private Context mContext;
    private EditText phoneEdit;
    private EditText codeEdit;

    private Button codeButton;
    private Button sureButton;
    private TimeCount time;
    private String mPhone;
    private String mCode;
//    private String mPsw;
//    private String mRepeatPsw;
    private int getCodeTaskId = -1;
    private int forgetPswTaskId = -1;
    private int initId;
    private String localPsw;
    private TextView back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bangdingphone);
        time = new TimeCount(90000, 1000);
        mContext = this;
        initView();
    }

    private void initView() {

        phoneEdit = (EditText) findViewById(R.id.bangding_phone);
        codeEdit = (EditText) findViewById(R.id.bangding_code);

        codeButton = (Button) findViewById(R.id.forget_code_button);
        sureButton = (Button) findViewById(R.id.bangding_btn);
        back= (TextView) findViewById(R.id.back);
        back.setOnClickListener(this);
        codeButton.setOnClickListener(this);
        sureButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.forget_code_button:
                if (checkInputBeforeSMS()) {
                    getPhoneCode();
                }
                break;
            case R.id.bangding_btn:
                if (checkInput()) {
                    doBangding();
                }
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    private void getPhoneCode() {
        GetVerifyCodeTask task = new GetVerifyCodeTask(mPhone, "2");
        task.addListener(new ForgetPswTaskEventListener(mContext));
        getCodeTaskId = getEatShowApp().getTaskManager().addTask(task);
        time.start();
    }

    private void doBangding() {
        BangDingShouJiTask task = new BangDingShouJiTask(mPhone, mCode);
        task.addListener(new ForgetPswTaskEventListener(mContext));
        forgetPswTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    class ForgetPswTaskEventListener extends ShowToastTaskEventListener {

        public ForgetPswTaskEventListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == forgetPswTaskId) {
                ToastUtil.showMessage(BangDingPhoneActivity.this,"绑定成功");
                forgetPswTaskId = -1;
                if(getEatShowApp().getmUserInfo()!=null){
                    getEatShowApp().getmUserInfo().setPhoneNum(mPhone);

                }
                Intent intent = new Intent();
                intent.putExtra("PHONE", mPhone);
                //设置返回数据
                BangDingPhoneActivity.this.setResult(RESULT_OK, intent);
                //关闭Activity
                BangDingPhoneActivity.this.finish();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == getCodeTaskId) {
                getCodeTaskId = -1;
                time.cancelTime();
            }
        }

    }

    private boolean checkInputBeforeSMS() {
        mPhone = phoneEdit.getText().toString();
        if (TextUtils.isEmpty(mPhone) || mPhone.length() != PHONE_LENGTH
                || !mPhone.matches(PHONE_REGEX)) {
            Toast.makeText(mContext, R.string.no_phone, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    private boolean checkInput() {
        mCode = codeEdit.getText().toString();

            if (TextUtils.isEmpty(mCode)
                    || mCode.length() != CODE_LENGTH) {
                Toast.makeText(mContext, R.string.no_code, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }

        return true;
    }


    /**
     * 方法作用：倒计时
     */
    class TimeCount extends CountDownTimer {

        // 参数依次为总时长,和计时的时间间隔
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            codeButton.setText(mContext.getString(R.string.get_vfcode));
            codeButton.setClickable(true);
            codeButton.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            codeButton.setClickable(false);
            codeButton.setEnabled(false);
            codeButton.setText(String.format(
                    mContext.getString(R.string.get_vfcode_new),
                    millisUntilFinished / 1000));
        }

        public void cancelTime() {// 取消计时
            time.cancel();
            codeButton.setText(mContext.getString(R.string.get_vfcode));
            codeButton.setClickable(true);
            codeButton.setEnabled(true);
        }

    }
}
